/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.starter.integration.spring.bean;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Set;

/**
 * @author william
 * @since 2024/1/16
 */
public abstract class AbstractSimpleBeanDefRegistrar implements ImportBeanDefinitionRegistrar {
    private final transient BeanNameGenerator beanNameGenerator;
    private final transient CandidateBeanDefSetBuilder beanDefSetBuilder;

    protected AbstractSimpleBeanDefRegistrar(BeanNameGenerator beanNameGenerator, Environment environment,
                                             ResourceLoader resourceLoader) {
        this.beanNameGenerator = beanNameGenerator;
        this.beanDefSetBuilder = CandidateBeanDefSetBuilder.newBuilder(environment, resourceLoader);
    }

    protected AbstractSimpleBeanDefRegistrar(Environment environment, ResourceLoader resourceLoader) {
        this(PajamasBeanNameGenerator.INSTANCE, environment, resourceLoader);
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        this.doRegisterBeanDefinitions(importingClassMetadata, this.beanDefSetBuilder);
        Set<BeanDefinition> beanDefinitions = this.beanDefSetBuilder.build();
        if (CollectionUtils.isNotEmpty(beanDefinitions)) {
            for (BeanDefinition beanDefinition : beanDefinitions) {
                String beanName = this.beanNameGenerator.generateBeanName(beanDefinition, registry);
                this.register(registry, beanName, beanDefinition);
            }
        }
    }

    protected abstract void doRegisterBeanDefinitions(AnnotationMetadata importingClassMetadata,
                                                      CandidateBeanDefSetBuilder beanDefSetBuilder);

    private void register(BeanDefinitionRegistry registry, String beanName, BeanDefinition beanDef) {
        registry.registerBeanDefinition(beanName, beanDef);
    }
}
